package cn.itsource.basic.controller;

import cn.itsource.basic.util.AjaxResult;
import cn.itsource.basic.util.FastdfsUtil;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

@RestController
@RequestMapping("/fastDfs")
public class FastDfsController {

    @PostMapping("/upload")
    public AjaxResult upload(@RequestPart(name = "file") MultipartFile file){
        try {
            String filename = file.getOriginalFilename();//文件全名  xxoo.jpg
            String ext = filename.substring(filename.lastIndexOf(".") + 1);// jpg

            String path = FastdfsUtil.upload(file.getBytes(), ext);// 返回给我们的路劲： /group1/M00/03/01/CgAIC2OF2wSAQJ-GAAIsyhup4R8212.jpg
            return AjaxResult.me().setResultObj(path);
        } catch (IOException e) {
            e.printStackTrace();
            return AjaxResult.me().setSuccess(false).setMessage("上传文件失败");
        }
    }

    @DeleteMapping()// http:localhost:8080/fastDfs?path= /group1/M00/03/01/CgAIC2OF2wSAQJ-GAAIsyhup4R8212.jpg
    //@RequestParam需要前端以这种格式来传参?k=v&k1=v1
    public AjaxResult delete(@RequestParam(value = "path") String path){

        try {
            String pathTmp = path.substring(1); // group1/M00/03/01/CgAIC2OF2wSAQJ-GAAIsyhup4R8212.jpg
            String groupName =  pathTmp.substring(0, pathTmp.indexOf("/")); //  group1
            String remotePath = pathTmp.substring(pathTmp.indexOf("/")+1);// M00/03/01/CgAIC2OF2wSAQJ-GAAIsyhup4R8212.jpg
            System.out.println(groupName);
            System.out.println(remotePath);
            //调用工具类删除
            FastdfsUtil.delete(groupName,remotePath);
            return AjaxResult.me();
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me().setSuccess(false).setMessage("文件删除失败");
        }
    }


}
